import { ElMessage } from 'element-plus';

export interface ResOptions<T> {
  data: T;
  code: number;
  message: string;
}

export default $fetch.create({
  // 请求拦截器
  onRequest({ options }) {
    const config = useRuntimeConfig();
    options.baseURL = config.public.apiBase;
    // 添加请求头,没登录不携带token
    const userStore = useUserStore();
    if (userStore.token) options.headers.set('Authorization', `Bearer ${userStore.token}`);
  },
  // 响应拦截
  onResponse({ response, options }) {
    // 重新登录
    if (response?._data?.code === 401) {
      useUserStore().onLogout();
      ElMessage.error('登录失效，请重新登录');
      navigateTo('/login', { replace: true });
      return Promise.reject(new Error());
    }
    // 判断错误
    if (String(response?._data?.code)?.[0] !== '2') {
      ElMessage.error(response._data.message as string);
      return Promise.reject(new Error(response._data?.message as string));
    }
    return response._data;
  },
});
